<template>
  <view class="view_box">
    <navBar :navbarData.sync="navbarData"></navBar>
    <view v-if="showTips === 1 && utoolsData">
      <utools-parse id="utools-parse" page="category" @triggerComponent="onTriggerComponent" @setPanel="setPanel"
        :utools-data="utoolsData" @onAddCart="onAddCart"></utools-parse>
    </view>
    <view v-if="showTips === 2" class="no_text">
      暂无内容
    </view>
    <cart-toast v-if="showCartMsg" :cartMessage='cartMessage' :cartStatus='cartStatus' bottom="0"></cart-toast>
    <view class="ios_safe_zone" v-if="isIos &&isBar">
      <view class="ios_safe_zone_line"></view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>

<script>
  let observer = null;
  import api from '@/api/api';
  import {
    SEL_CLASS_CODE,
    SEL_ACTIVE_CODE,
    SYSTEM_INFO,
    USER_INFO,
    CUSTOMER_INFO,
    CUSTOMER_HOTFIX,
    CART_KEY,
    MERCHANT_INFO,
    USER_SPECICAL_INFO
  } from '@/utils/constant';
  import NavBar from '../../components/common/navbar';
  import CartToast from '@/components/common/cartToast';
  export default {
    components: {
      navBar: NavBar,
      CartToast
    },
    data() {
      return {
        utoolsClassGoodsLists: null,
        utoolsData: null,
        showTips: 0,
        navbarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          title: '',
          navbarTitle: ''
        },
        cartMessage: '',
        cartStatus: false,
        showCartMsg: false,
        isIos: false,
        shareImage: '',
        shareTitle: '',
        pagePath: '',
        pageQuery: '',
				isBar: true,
      };
    },
    async onLoad(option) {
      await this.init(option);
      this.isIos = wx.getSystemInfoSync().system.includes('iOS') && wx.getSystemInfoSync()?.safeArea?.top > 20;
    },
    onShow() {
      if (!observer) {
        const that = this
        let h = wx.getSystemInfoSync().windowHeight / 2;
        let w = wx.getSystemInfoSync().windowWidth / 2;
        setTimeout(() => {
          observer = wx.createIntersectionObserver(that, {
            observeAll: true,
            thresholds: [1]
          });

          observer.relativeToViewport({
            top: 150,
            bottom: 150,
            left: 0,
            right: 0
          }).observe('#utools-parse >>> .videos', (res) => {
            let dom = this.selectComponent(`#utools-parse >>> #${res.id}`)
            if (res.intersectionRatio === 1) {
              dom.onAppear()
            } else {
              dom.onDisappear()
            }
          })
        }, 3000)
      }
    },
    onUnload() {
      if (observer) observer.disconnect()
      observer = null
    },
    onHide() {
      if (observer) observer.disconnect()
      observer = null
    },
    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      async init(option) {
        const that = this;
        if (option && option.uttype) {

			this.isBar= option.isBar ? false : true
          this.getPageShareData(option);
          let _utoolsData = await this.getUtoolsData(option);
          if (_utoolsData.children.length > 0 && _utoolsData.children[0].trackingParams) {
            try {
              this.$commonUtoolsTrack.sensorsTracking(_utoolsData.children[0].trackingParams);
            } catch (e) {
              console.log("###### utcms-onTriggerComponent-error:", e)
            }
          }
          if (!_utoolsData) return this.showTips = 2;
          if (_utoolsData.classId) {
            //商品
            let uLists = await this.getCateGoods(_utoolsData.classId);
            that.utoolsClassGoodsLists = uLists;
            //下面是有数埋点
            if (uLists.length > 0) {
              let merchantInfo = wx.getStorageSync('merchantInfo')
              const _openOuterItemId = wx.getStorageSync('openOuterItemId');
              const _youshuOpencc = wx.getStorageSync('youshuOpencc');
              for (let i = 0; i < uLists.length; i++) {
                if (uLists[i].skuCodes !== undefined) {
                  that.srTrackExposeSkuComponent(uLists[i], _youshuOpencc, _openOuterItemId, merchantInfo
                    .cloudMerchantId)
                }
              }
            }
          }
          this.utoolsData = _utoolsData;
          this.showTips = 1;
        } else {
          //  暂无utools数据 展示空内容页
          this.showTips = 2;
        }
        return null
      },
      /**
       * 查询分享数据
       * @param {Object} option
       */
      async getPageShareData(option) {
        try {
          let shareCode = "";
          if (option) shareCode = option.utid ? option.uttype + option.utid : option.uttype;
          const res = await this.$commonFunction.getShareinfoByCode(shareCode);
          this.shareImage = res.shareImage;
          this.shareTitle = res.shareTitle;
          this.pagePath = res.pagePath; //  当前页面路由
          this.pageQuery = res.pageQuery; //  当前页面url参数
        } catch (e) {}
      },
      /**
       * 获取utools数据
       * @param {Object} option
       */
      async getUtoolsData(option) {
        try {
          let json;
          if (option?.utpreview && option?.utid) {
            //  是否预览
            json = await api.getUtoolsJsonP({
              utoolsId: option.utid,
              type: option.uttype
            });
          } else if (option?.utid) {
            // 根据id获取数据
            json = await api.getUtoolsJsonById({
              utoolsId: option.utid
            });
          } else {
            //  根据类型获取数据
            json = await api.getUtoolsJson({
              type: option.uttype
            });
          }
          return json.success && json?.data ? JSON.parse(json.data) : null;
        } catch (e) {
          return null;
        }
      },
      /**
       * 查询首页商品分类列表
       * @param {Object} class_id
       * @param {Object} is_sort
       */
      async getCateGoods(class_id, is_sort) {
        try {
          //获取商品
          let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
          let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
          let res = await this.$commonFunction.doSearchGoods(class_id, '', 1, 200, null, '', is_sort, '', '', '', '',
            true)
          let cateProductList = res.data.content; // 商品列表
          //sku实时库存查询
          let skuCodeList = [],
            goodsQ = [];
          for (let i = 0; i < cateProductList.length; i++) {
            skuCodeList = skuCodeList.concat(cateProductList[i].skuCodes)
          }

          if (skuCodeList.length) {
            skuCodeList = await this.setSkuCodeList(skuCodeList)
            for (let i = 0; i < skuCodeList.length; i++) {
              let reset = await this.getAvailableBatchQty(customerInfo, merchantInfo, skuCodeList[i]);
              goodsQ = reset.length ? goodsQ.concat(reset) : goodsQ
            }
          }
          let list = [];
          cateProductList = cateProductList.map(async item => {
            let res = await this.$commonFunction.priceRulesDeal(item.strategies, item.itemmCode)
            if (goodsQ && goodsQ.length) {
              for (let i = 0; i < goodsQ.length; i++) {
                if (item.skuCodes.indexOf(goodsQ[i].skuCode) !== -1 && goodsQ[i].availableQty > 0) {
                  item.frontQty += goodsQ[i].availableQty
                }
              }
            }
            if (res.price !== 0) {
              if (item.itemCode == res.itemCode) {
                item.price = res.price
              }
            }
            if (res.rulesArr.length > 0) {
              if (item.itemCode == res.itemCode) {
                item.rulesArr = res.rulesArr
              }
            }
            // var isForwardpurchaseGoods = false;
            // let  customPromotionTags = item['promotionTagList']?.map(ite=>{
            // 	if (ite.promotionType == 'custom_tag') {
            // 	  customPromotionTags.push(tagItem);
            // 	}

            // 	if (tagItem.promotionType == 'forward_purchase') {
            // 	  isForwardpurchaseGoods = true;
            // 	}
            // 	return ite.promotionType == 'custom_tag'? ite : null
            // })
            list.push(item)
            return item
          })
          return list
        } catch (err) {
          console.log("###### home-getCateGoods-error:", err)
          return null
        }
      },
      async setSkuCodeList(skuCodeList) {
        if (skuCodeList.length < 21) {
          return [skuCodeList]
        } else {
          const result = skuCodeList.flatMap((value, index, array) => {
            if (index % 20 === 0) {
              return [array.slice(index, index + 20)];
            }
            return [];
          });
          return result
        }
      },
      /**
       * 查询有效库存
       * @param {Object} customerInfo
       * @param {Object} merchantInfo
       * @param {Object} skuCodeList
       */
      async getAvailableBatchQty(customerInfo, merchantInfo, skuCodeList) {
        let reset = await api.getAvailableBatchQty({
          method: "POST",
          header: {
            jwt: customerInfo.jwt,
            'content-type': 'application/json'
          },
          query: skuCodeList
          // query: JSON.stringify(skuCodeList)
        }, merchantInfo.cloudMerchantId);
        if (reset.msg == "SUCCESS" && reset?.data?.length) {
          return reset.data.filter(item => item.availableQty > 0)
        } else {
          return []
        }
      },
      //商品和购物车有数埋点2
      onTriggerComponent(e) {
        try {
          this.$commonUtoolsTrack.onTriggerComponent(e);
        } catch (e) {
          console.log("home-onTriggerComponent-error:", e)
        }
      },
      /**
       * utools加入购物车回调
       * @param {Object} e
       */
      async onAddCart(e) {
        const {
          detail: {
            data
          }
        } = e;
        this.addCart(data);
      },
			//	商品加购
			async addCart(data){
				if (!data || !data.itemId) return this.handleCartToast({
					success: false,
					msg: "加入购物袋失败"
				});
				const merchantInfo = uni.getStorageSync('merchantInfo');
				if (!merchantInfo) return this.handleCartToast({
					success: false,
					msg: "加入购物袋失败"
				});
				// 获取商品详情
				const goodsInfo = await this.getGoodsDetail(merchantInfo, data.itemId);
				if (!goodsInfo || goodsInfo.code != 1000) return this.handleCartToast({
					success: false,
					msg: "加入购物袋失败"
				});
				const cartRes = await this.$commonFunction.buildProductsAddCart({
					price: goodsInfo.data.skus[0].price,
					itemId: goodsInfo.data.itemId,
					valueId: goodsInfo.data.frontProperties[0].valueId,
					itemCode: goodsInfo.data.itemId,
					itemName: goodsInfo.data.itemName,
					qty: 1,
					skuCode: goodsInfo.data.skus[0].skuCode,
					skuId: goodsInfo.data.skus[0].skuId,
				});
				//  加入购物车提示
				this.handleCartToast(cartRes);
			},
      /**
       * 加购提示
       * @param {Object} obj
       */
      async handleCartToast(obj) {
				const _arr = ['您动作太快，请慢点哟～', '网络状态不佳，请重试'];
				if(obj.msg && _arr.includes(obj.msg)){
					this.handleShowTextToast(obj.msg)
				}else if(obj.data && obj.data.msg && obj.data.type === 'showToast'){
					this.handleShowTextToast(obj.data.msg)
				}else{
					this.cartMessage = obj?.msg || "加入购物袋失败";
					this.cartStatus = obj?.success || false;
					this.showCartMsg = true;
					setTimeout(() => {
						this.showCartMsg = false;
					}, 3000);
				}
      },
      //根据商品id获取商品详情
      async getGoodsDetail(merchantInfo, itemId) {
        return await api.goodsDetail({
          query: {
            merchant_id: merchantInfo.cloudMerchantId,
            store_id: merchantInfo.cloudMerchantStoreId
          }
        }, itemId);
      },
      /**
       * 腾讯有数埋点
       * @param {Object} item
       * @param {Object} type
       */
      srTracking(item, type) {
        try {
          let merchantInfo = uni.getStorageSync('merchantInfo');
          let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
          let userInfo = uni.getStorageSync(USER_INFO);
          const _openOuterItemId = wx.getStorageSync('openOuterItemId');
          const _youshuOpencc = wx.getStorageSync('youshuOpencc');
          if (type == 'itemClick') {
						const spuid = !!_openOuterItemId ? item.outerItemId : !!_youshuOpencc ? item.frontProperties[0].frontCode?.toString() : item.itemCode?.toString();
						const spuname = !!_youshuOpencc ? item.itemName + item.frontProperties?.[0].valueName : item.itemName;
            getApp().globalData.$sr.track('trigger_sku_component', {
              "sku": {
                "sku_id": item.skuCodes[0]?.toString(),
                "sku_name": item.itemName
              },
              "spu": {
                "spu_id": spuid || item.skuCodes[0]?.toString(),
                "spu_name": spuname || item.itemName // 若商品无spu_name时，可传sku_name信息
              },
              "sku_category": [{
                "sku_cat_id": item.categoryId?.toString(),
                "sku_cat_name": "11",
                "sku_parent_cat_id": "null" // 若已是顶级类目，传"null"
              }],
              "shipping_shop": {
                "shipping_shop_id": merchantInfo.cloudMerchantId + '', // 到家类型对接智慧零售入口必传
                "shipping_shop_name": "THE MACALLAN EBOUTIQUE麦卡伦" // 到家类型对接智慧零售入口必传
              },
              // "sale": {
              // 	"original_price": parsefloor(item.price), // 对接智慧零售入口必传
              // 	"current_price": parsefloor(item.markingPrice) // 对接智慧零售入口必传
              // },
              "primary_image_url": item.skuImageUrl
            });
            this.$commonSensors.PLPProductClick(item, "", "");
          } else if (type == "addCartClick") {
            //这里是购物车
            getApp().globalData.$sr.track('add_to_cart', {
              "action_type": 'append_to_cart',
              "sku": {
                "sku_id": item.skuCodes[0].toString(),
                "sku_name": item.itemName
              },
              "spu": {
                "spu_id": !!_openOuterItemId ? item.outerItemId : !!_youshuOpencc ? item.frontProperties[0]
                  .frontCode?.toString() : item.itemCode?.toString(),
                "spu_name": !!_youshuOpencc ? item.itemName + item.frontProperties?.[0].valueName : item
                  .itemName // 若商品无spu_name时，可传sku_name信息
              },
              "sku_category": [{
                "sku_cat_id": item.categoryId?.toString(),
                "sku_cat_name": "11",
                "sku_parent_cat_id": "null" // 若已是顶级类目，传"null"
              }],
              "shipping_shop": {
                "shipping_shop_id": merchantInfo.cloudMerchantId + '', // 到家类型对接智慧零售入口必传
                "shipping_shop_name": "THE MACALLAN EBOUTIQUE麦卡伦" // 到家类型对接智慧零售入口必传
              },
              // "sale": {
              // 	"original_price": parsefloor(item.price), // 对接智慧零售入口必传
              // 	"current_price": parsefloor(item.markingPrice) // 对接智慧零售入口必传
              // },
              "sku_num": 1,
              "primary_image_url": item.skuImageUrl
            })
            this.$commonSensors.addToCartMF(item, 1, ['常规']);
          }
        } catch (e) {
          console.log("###### utcms-srTracking-error:", e)
        }
      },
      /**
       * 腾讯有数商品曝光埋点
       * @param {Object} item
       * @param {Object} _youshuOpencc
       * @param {Object} _openOuterItemId
       */
      srTrackExposeSkuComponent(item, _youshuOpencc, _openOuterItemId, cloudMerchantId) {
        try {
          this.$sr.track('expose_sku_component', {
            sku: {
              sku_id: item.skuCodes[0].toString(),
              sku_name: item.itemName // 若商品无sku_name时，可传spu_name信息
            },
            spu: {
              spu_id: !!_openOuterItemId ? item.outerItemId : !!_youshuOpencc ? item.frontCode.toString() : item
                .itemCode.toString(),
              spu_name: !!_youshuOpencc ? item.itemName + item.valueName : item
                .itemName // 若商品无spu_name时，可传sku_name信息
            },
            sku_category: [{
              sku_cat_id: item.categoryId.toString(),
              sku_cat_name: '全部商品',
              sku_parent_cat_id: 'null' // 若已是顶级类目，传"null"
            }],
            shipping_shop: {
              shipping_shop_id: cloudMerchantId.toString(), // 到家类型对接智慧零售入口必传
              shipping_shop_name: "THE MACALLAN EBOUTIQUE麦卡伦" // 到家类型对接智慧零售入口必传
            },
            sale: {
              original_price: parseFloat(item.price), // 对接智慧零售入口必传
              current_price: parseFloat(item.price) // 对接智慧零售入口必传
            },
            primary_image_url: item.majorUrl
          });
        } catch (e) {

        }
      },
      onShareAppMessage(res) {
        let that = this
        if (res.from === 'button') {} else {
          this.$EFSTracking.trackingAction('SHARE_CARD', res.from, {});
        }
        let imageUrl = this.shareImage;
        let path = this.pageQuery ? `/${this.pagePath}?${this.pageQuery}` : `/${this.pagePath}`;
        let title = this.shareTitle;
        this.$commonSensors.sensorsPageShare();
				this.$sr.setContext({ share_title: title || 'THE MACALLAN EBOUTIQUE麦卡伦' });
        return this.$commonFunction.commonShare(res, this.shareTitle, path, this.shareImage);
      },
      onShareTimeline() {
				const title = this.shareTitle ? this.shareTitle : uni.getStorageSync('storeName') || 'THE MACALLAN EBOUTIQUE麦卡伦';
				this.$sr.setContext({ share_title: title || 'THE MACALLAN EBOUTIQUE麦卡伦' });
        return {
          title: title,
          query: this.pageQuery,
          imageUrl: this.shareImage
        };
      },
    }
  }
</script>

<style lang="less">
  .view_box {
    position: relative;
  }

  .no_text {
    width: 100%;
    text-align: center;
    font-family: NotoSansSC-Regular;
    font-size: 28rpx;
    font-weight: 500;
    margin-top: 300rpx;
    color: #757575;
  }
</style>
